import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Button, DatePicker, Modal, message, Divider } from 'antd';
import StandardTable from 'components/StandardTable';
import DictSelect from 'components/DictSelect';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from '../List/TableList.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ sysNotice, dictionary, loading }) => ({
  sysNotice,
  dictionary,
  loading: loading.models.sysNotice,
}))
@Form.create()
export default class SysNoticeList extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
    enablePublishRows: [], // 可发布的通知
    enableDownRows: [], // 可下架的通知
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysNotice/fetch',
    });

    dispatch({
      type: 'dictionary/loadDict',
      codetype: 'notice.type',
    });
    dispatch({
      type: 'dictionary/loadDict',
      codetype: 'notice.status',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current - 1,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'sysNotice/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'sysNotice/fetch',
      payload: {},
    });
  };

  handleRemove = () => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    const onOkf = () => {
      dispatch({
        type: 'sysNotice/remove',
        payload: {
          ids: selectedRows.map(row => row.nid).join(','),
        },
        callback: () => {
          this.setState({
            selectedRows: [],
            enablePublishRows: [],
            enableDownRows: [],
          });
          message.info('已成功删除');
          this.doSearch();
        },
      });
    };
    Modal.confirm({
      title: '删除',
      content: '确定永久删除选定的记录吗？',
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: onOkf,
      onCancel() {
        // console.log('Cancel');
      },
    });
  };

  handlePublish = () => {
    const { dispatch } = this.props;
    const { enablePublishRows } = this.state;

    if (!enablePublishRows) return;
    const onOkf = () => {
      dispatch({
        type: 'sysNotice/publish',
        payload: {
          ids: enablePublishRows.map(row => row.nid).join(','),
        },
        callback: () => {
          this.setState({
            selectedRows: [],
            enablePublishRows: [],
            enableDownRows: [],
          });
          message.info('已成功发布');
          this.doSearch();
        },
      });
    };
    Modal.confirm({
      title: '发布通知',
      content: '选中的记录里共有' + enablePublishRows.length + '条通知可发布，确定发布吗？',
      okText: '确定发布',
      okType: 'primary',
      cancelText: '取消',
      onOk: onOkf,
      onCancel() {
        // console.log('Cancel');
      },
    });
  };

  handleDown = () => {
    const { dispatch } = this.props;
    const { enableDownRows } = this.state;

    if (!enableDownRows) return;
    const onOkf = () => {
      dispatch({
        type: 'sysNotice/downout',
        payload: {
          ids: enableDownRows.map(row => row.nid).join(','),
        },
        callback: () => {
          this.setState({
            selectedRows: [],
            enablePublishRows: [],
            enableDownRows: [],
          });
          message.info('已成功下架');
          this.doSearch();
        },
      });
    };
    Modal.confirm({
      title: '下架通知',
      content: '选中的记录里共有' + enableDownRows.length + '条通知可下架，确定下架吗？',
      okText: '确定下架',
      okType: 'primary',
      cancelText: '取消',
      onOk: onOkf,
      onCancel() {
        // console.log('Cancel');
      },
    });
  };

  handleSelectRows = rows => {
    const publishRows = [];
    const downRows = [];
    rows.forEach(rec => {
      const { nstatus } = rec;
      if (nstatus === '2') {
        // 状态=待发布，允许显示发布按钮
        publishRows.push(rec);
      } else if (nstatus === '3') {
        // 状态=已发布，运行显示下架按钮
        downRows.push(rec);
      }
    });

    this.setState({
      selectedRows: rows, // 所有已选择的记录
      enablePublishRows: publishRows, // 选择的记录中可发布的记录
      enableDownRows: downRows, // 选择的记录中可下架的记录
    });
  };

  doSearch = () => {
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        createTime: null,
        updateTime: null,
        ge_createTime:
          fieldsValue.createTime && fieldsValue.createTime[0].format('YYYY-MM-DD HH:mm:ss'),
        le_createTime:
          fieldsValue.createTime && fieldsValue.createTime[1].format('YYYY-MM-DD HH:mm:ss'),
        ge_updateTime:
          fieldsValue.updateTime && fieldsValue.updateTime[0].format('YYYY-MM-DD HH:mm:ss'),
        le_updateTime:
          fieldsValue.updateTime && fieldsValue.updateTime[1].format('YYYY-MM-DD HH:mm:ss'),
      };

      // console.log(values)

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'sysNotice/fetch',
        payload: values,
      });
    });
  };

  handleSearch = e => {
    e.preventDefault();

    this.doSearch();
  };

  handleShow = (e, key) => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push(`/sys/sysNotice-profile/${key}`));
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push(`/sys/sysNotice-form/add/0`));
  };

  handleEdit = (e, key) => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push(`/sys/sysNotice-form/edit/${key}`));
  };

  renderAdvancedForm() {
    const { dictionary, form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="通知类型">
              {getFieldDecorator('eq_ntype')(
                <DictSelect
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  dictList={dictionary['notice.type']}
                />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="通知标题">
              {getFieldDecorator('like_title')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="通知状态">
              {getFieldDecorator('eq_nstatus')(
                <DictSelect
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  dictList={dictionary['notice.status']}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem label="创建时间">
              {getFieldDecorator('createTime')(
                <RangePicker
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                />
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem label="更新时间<=">
              {getFieldDecorator('updateTime')(
                <RangePicker
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button icon="search" type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </span>
        </div>
      </Form>
    );
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    const {
      sysNotice: { data },
      loading,
    } = this.props;
    const { selectedRows, enablePublishRows, enableDownRows } = this.state;

    const columns = [
      {
        title: '通知id',
        dataIndex: 'nid',
      },
      {
        title: '通知类型',
        dataIndex: 'ntypeName',
      },
      {
        title: '通知标题',
        dataIndex: 'title',
      },
      // {
      //   title: '通知内容',
      //   dataIndex: 'content',
      // },
      // {
      //   title: '通知banner图',
      //   dataIndex: 'picBanner',
      // },
      // {
      //   title: '创建人',
      //   dataIndex: 'createUser',
      // },
      // {
      //   title: '创建时间',
      //   dataIndex: 'createTime',
      // },
      // {
      //   title: '更新人员',
      //   dataIndex: 'updateUser',
      // },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
      },
      {
        title: '通知状态',
        dataIndex: 'nstatusName',
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={e => this.handleEdit(e, record.nid)}>编辑</a>
            <Divider type="vertical" />
            <a onClick={e => this.handleShow(e, record.nid)}>查看</a>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={this.handleAdd}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button icon="minus" type="dashed" onClick={this.handleRemove}>
                    删除
                  </Button>
                </span>
              )}
              {enablePublishRows.length > 0 && (
                <span>
                  <Button icon="play-circle" type="primary" onClick={this.handlePublish}>
                    发布
                  </Button>
                </span>
              )}
              {enableDownRows.length > 0 && (
                <span>
                  <Button icon="down-circle-o" type="default" onClick={this.handleDown}>
                    下架
                  </Button>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey="nid"
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
